from sqlalchemy.future import select
from domain.models.models import UserAuth
from domain.models.models import User
from db.db import async_session

async def create_user_auth(user_id: int, real_name: str, id_number: str, id_front_url: str, id_back_url: str) -> tuple[bool, str]:
    """创建用户实名认证信息"""
    try:
        async with async_session() as session:
            # 检查是否已经提交过认证
            stmt = select(UserAuth).where(UserAuth.user_id == user_id)
            result = await session.execute(stmt)
            existing_auth = result.scalar_one_or_none()

            if existing_auth:
                return False, "已提交过认证信息", 0

            # 创建新的认证记录
            auth_info = UserAuth(
                user_id=user_id,
                real_name=real_name,
                id_number=id_number,
                id_front_url=id_front_url,
                id_back_url=id_back_url,
                auth_status=0  # 待审核状态
            )
            session.add(auth_info)
            await session.commit()
            return True, "提交成功，等待审核", auth_info.id

    except Exception as e:
        return False, str(e), 0

async def get_user_auth_status(user_id: int) -> tuple[bool, dict]:
    """获取用户认证状态"""
    try:
        async with async_session() as session:
            stmt = select(UserAuth).where(UserAuth.user_id == user_id)
            result = await session.execute(stmt)
            auth_info = result.scalar_one_or_none()

            if not auth_info:
                return False, {"msg": "未提交认证信息"}

            return True, {
                "auth_status": auth_info.auth_status,
                "remark": auth_info.remark
            }

    except Exception as e:
        return False, {"msg": str(e)}

async def update_auth_status(auth_id: int, auth_status: int, remark: str = "") -> tuple[bool, str]:
    """更新认证状态"""
    try:
        async with async_session() as session:
            stmt = select(UserAuth).where(UserAuth.id == auth_id)
            result = await session.execute(stmt)
            auth_info = result.scalar_one_or_none()

            if not auth_info:
                return False, "认证信息不存在"

            auth_info.auth_status = auth_status
            auth_info.remark = remark

            # 更新用户的认证状态
            if auth_status == 1:  # 认证通过
                stmt = select(User).where(User.id == auth_info.user_id)
                result = await session.execute(stmt)
                user = result.scalar_one_or_none()
                if user:
                    user.is_auth = 1

            await session.commit()
            return True, "审核完成"

    except Exception as e:
        return False, str(e)